const express = require("express");
const router = express.Router();
const passport = require("passport");
const moment = require("moment");

const Profile = require("../../models/Profile");

// Get test 测试接口 api/profiles/test
router.get("/test", (req, res) => res.json({ msg: "Profile Works" }));

// Post add 添加信息接口 api/profiles/add
router.post(
  "/add",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const profileFields = {};

    if (req.body.profile_state)
      profileFields.profile_state = req.body.profile_state;
    if (req.body.profile_title)
      profileFields.profile_title = req.body.profile_title;
    if (req.body.create_time)
      profileFields.create_time = moment(req.body.create_time).format(
        "YYYY-MM-DD"
      );
    if (req.body.finish_time)
      profileFields.finish_time = moment(req.body.finish_time).format(
        "YYYY-MM-DD"
      );
    if (req.body.amount) profileFields.amount = req.body.amount;
    if (req.body.persons) profileFields.persons = req.body.persons;

    new Profile(profileFields)
      .save()
      .then((profile) => res.json(profile))
      .catch((err) => res.status(400).json(err));
  }
);

// Get "/" 获取所有项目信息 api/profiles/
router.get(
  "/",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Profile.find()
      .populate("persons.person")
      .then((profiles) => res.json(profiles))
      .catch((err) => res.status(404).json("没有找到任何项目"));
  }
);

// Get "/:id" 获取单个项目信息 api/profiles/:id
router.get(
  "/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Profile.findById({ _id: req.params.id })
      .then((profiles) => res.json(profiles))
      .catch((err) => res.status(404).json("没有找到项目!"));
  }
);

// Post edit 编辑单个信息 api/profiles/edit/:id
router.post(
  "/edit/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    const profileFields = {};

    if (req.body.profile_state)
      profileFields.profile_state = req.body.profile_state;
    if (req.body.profile_title)
      profileFields.profile_title = req.body.profile_title;
    if (req.body.create_time) profileFields.create_time = req.body.create_time;
    if (req.body.finish_time) profileFields.finish_time = req.body.finish_time;
    if (req.body.amount) profileFields.amount = req.body.amount;
    if (req.body.persons) profileFields.persons = req.body.persons;

    Profile.findOneAndUpdate(
      { _id: req.params.id }, // 查询这个项目id
      { $set: profileFields }, // 设置内容
      { new: true } // 新东西
    ).then((profile) => res.json(profile));
  }
);

// Delete '/delete' 删除单个信息 api/profiles/delete/:id
router.delete(
  "/delete/:id",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    Profile.findOneAndDelete({ _id: req.params.id })
      .then((profile) => res.json(profile))
      .catch((err) => res.status(404).json("删除失败！"));
  }
);

module.exports = router;
